package com.yugao.fintech.framework.mybatismate.fieldunique;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
@ConditionalOnClass(value = {RedisTemplate.class})
@ConditionalOnMissingBean(IFieldUniqueCheckLock.class)
public class FieldUniqueCheckRedisLock implements IFieldUniqueCheckLock {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    private static final String pre = "field_unique::";

    @Override
    public boolean lock(String cacheKey) throws Exception {
        Boolean success = redisTemplate.opsForValue().setIfAbsent(pre + cacheKey, "", 5, TimeUnit.MINUTES);
        return Boolean.TRUE.equals(success);
    }

    @Override
    public void unlock(String cacheKey) {
        redisTemplate.delete(pre + cacheKey);
    }
}
